<template>
  <div class="leaderboard-container">
    <div class="leaderboard-header">
      <h3 class="leaderboard-title">社区积分排行榜</h3>
      <div class="leaderboard-refresh" @click="refreshLeaderboard">
        <i class="fas fa-sync-alt" :class="{ 'rotating': loading }"></i>
      </div>
    </div>
    
    <div v-if="loading" class="leaderboard-loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-else-if="error" class="leaderboard-error">
      <i class="fas fa-exclamation-circle"></i>
      <p>{{ error }}</p>
      <button @click="refreshLeaderboard" class="retry-btn">重试</button>
    </div>
    
    <div v-else class="leaderboard-list">
      <div v-for="(user, index) in leaderboardData" :key="user.id" class="leaderboard-item">
        <div class="rank" :class="getRankClass(index)">{{ index + 1 }}</div>
        <div class="user-avatar">
          <img v-if="user.avatar" :src="user.avatar" alt="用户头像" />
          <div v-else class="default-avatar" :style="{ background: generateGradient(user.userName) }">
            {{ getUserInitial(user) }}
          </div>
        </div>
        <div class="user-info">
          <div class="user-name">{{ user.nickName || user.userName }}</div>
          <div class="stats">
            <span class="points">{{ user.points || 0 }} 积分</span>
            <span class="carbon">{{ user.carbonReduced || 0 }}kg 减碳量</span>
          </div>
        </div>
      </div>
      
      <div v-if="leaderboardData.length === 0" class="empty-state">
        暂无排行数据
      </div>
      
      <div v-if="!loading" class="load-more">
        <button @click="navigateToFullLeaderboard" class="load-more-btn">加载更多</button>
      </div>
    </div>
  </div>
</template>

<script>
import { getLeaderboard } from '@/api/auth';

export default {
  name: 'UserLeaderboard',
  props: {
    limit: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      loading: false,
      error: null,
      leaderboardData: [],
      currentPage: 1,
      pageSize: this.limit,
      total: 0,
      hasMore: false
    };
  },
  created() {
    this.fetchLeaderboard();
  },
  methods: {
    async fetchLeaderboard(append = false) {
      this.loading = true;
      this.error = null;
      
      try {
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize
        };
        
        const response = await getLeaderboard(params);
        
        if (response.success && response.data) {
          if (append) {
            // 将新数据附加到现有数据上
            this.leaderboardData = [...this.leaderboardData, ...(response.data.result || [])];
          } else {
            // 替换现有数据
            this.leaderboardData = response.data.result || [];
          }
          this.total = response.data.total || 0;
          this.hasMore = this.leaderboardData.length < this.total;
        } else {
          this.error = response.message || '获取排行榜失败';
        }
      } catch (error) {
        console.error('获取排行榜失败:', error);
        this.error = '获取排行榜失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    navigateToFullLeaderboard() {
      // 导航到完整的排行榜页面
      if (this.$router) {
        this.$router.push('/leaderboard');
      } else {
        window.location.href = '/leaderboard';
      }
    },
    getUserInitial(user) {
      const name = user.nickName || user.userName || '';
      if (!name) return '用';
      
      // 如果是中文名，取第一个字
      if (/[\u4e00-\u9fa5]/.test(name)) {
        return name.charAt(0);
      }
      
      // 如果是英文名，取首字母
      return name.charAt(0).toUpperCase();
    },
    generateGradient(username) {
      // 根据用户名生成一个固定的渐变色
      let hash = 0;
      const name = username || '';
      
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
      }
      
      // 确保哈希值为正
      hash = Math.abs(hash);
      
      // 生成两个颜色
      const hue1 = hash % 360;
      const hue2 = (hash * 7) % 360;
      
      return `linear-gradient(135deg, hsl(${hue1}, 70%, 60%), hsl(${hue2}, 70%, 60%))`;
    },
    getRankClass(index) {
      if (index === 0) return 'rank-first';
      if (index === 1) return 'rank-second';
      if (index === 2) return 'rank-third';
      return '';
    },
    refreshLeaderboard() {
      this.currentPage = 1;
      this.leaderboardData = [];
      this.fetchLeaderboard();
    }
  }
};
</script>

<style scoped>
.leaderboard-container {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 30px;
}

.leaderboard-header {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.leaderboard-title {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.leaderboard-refresh {
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.leaderboard-refresh:hover {
  background-color: rgba(76, 175, 80, 0.1);
}

.leaderboard-refresh i {
  color: #4CAF50;
  font-size: 16px;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.leaderboard-loading, .leaderboard-error {
  padding: 40px 0;
  text-align: center;
  color: #666;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid rgba(76, 175, 80, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.leaderboard-error i {
  font-size: 36px;
  color: #f44336;
  margin-bottom: 15px;
}

.retry-btn {
  margin-top: 15px;
  padding: 6px 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.leaderboard-list {
  padding: 10px 0;
}

.leaderboard-item {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  transition: background-color 0.2s;
}

.leaderboard-item:hover {
  background-color: #f9f9f9;
}

.rank {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #e0e0e0;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  margin-right: 15px;
  font-size: 14px;
}

.rank-first {
  background-color: #FFD700;
  color: white;
}

.rank-second {
  background-color: #C0C0C0;
  color: white;
}

.rank-third {
  background-color: #CD7F32;
  color: white;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 16px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 3px;
}

.stats {
  display: flex;
  font-size: 12px;
  color: #666;
}

.points {
  color: #4CAF50;
  font-weight: 500;
  margin-right: 15px;
}

.carbon {
  color: #2196F3;
}

.empty-state {
  text-align: center;
  padding: 30px;
  color: #666;
  font-style: italic;
}

.load-more {
  text-align: center;
  padding: 10px 0;
}

.load-more-btn {
  background: none;
  border: none;
  color: #4CAF50;
  cursor: pointer;
  font-size: 14px;
  padding: 5px 10px;
  border-radius: 4px;
}

.load-more-btn:hover {
  background-color: rgba(76, 175, 80, 0.1);
}

@media (max-width: 768px) {
  .leaderboard-item {
    padding: 10px 15px;
  }
  
  .user-avatar {
    width: 32px;
    height: 32px;
    margin-right: 10px;
  }
  
  .rank {
    width: 24px;
    height: 24px;
    font-size: 12px;
    margin-right: 10px;
  }
  
  .stats {
    flex-direction: column;
  }
  
  .points {
    margin-right: 0;
    margin-bottom: 2px;
  }
}
</style> 